<?
	// Setup Db
	require_once('dbController.php');
	require_once('glGlobals.php');	

	$glDb = new dbController($DB_CONNECT);

	$gameid = $_REQUEST['gameid'];
	
	//$SQL = "SELECT moveid FROM WHERE gameid = $gameid ORDER BY moveid DESC";
	
	$type = $_REQUEST['type'];
	
	// Get all the data to reinsert back into the database; we're just doing drag'n'drop update
	$SQL = "SELECT round, go, userturn,roundstarttime, word FROM roundstate WHERE gameid = $gameid ORDER BY moveid DESC";
	$result = $glDb->getRow($SQL);
	$round = $result[0];
	$go = $result[1];
	$userturn = $result[2];
	$time = $result[3];
	$word = $result[4];

	if($type == 'drop') {
		$dragid = '#' . $_REQUEST['dragid'];
		$dragsrc = $_REQUEST['dragsrc'];
		$SQL = "INSERT INTO roundstate (gameid, round, roundstarttime, action, data1, data2, go, userturn, word) VALUES ($gameid,$round,$time,'$type','$dragid','$dragsrc',$go,'$userturn','$word')";
		$glDb->query($SQL);
	}
	else if($type == 'query') {
		$query = $_REQUEST['query'];
		$SQL = "INSERT INTO roundstate (gameid, round, roundstarttime, action, data1, go, userturn, word) VALUES ($gameid,$round,$time,'$type','$query',$go,'$userturn','$word')";
		$glDb->query($SQL);
	}
	else if ($type == 'startgame') {
		$time = time();
		
		// Get new word
		$SQL = "SELECT word FROM wordlist";
		$words = $glDb->query($SQL);
		$wordIndex = rand()%($words->numRows());
		for($i = 0; $i<$wordIndex; $i++) {
			$words->fetchRow();
		}
		$theWord = $words->fetchRow();
		$word = $theWord[0];
		
		$SQL = "INSERT INTO roundstate (gameid, round, roundstarttime, action, data1, data2, go, userturn, word) VALUES ($gameid,$round,$time,'$type','$dragid','$dragsrc',1,'$userturn','$word')";
		$glDb->query($SQL);
		print($word);
	} else if($type == 'guess') {
		$guess = $_REQUEST['guess'];

		$SQL = "INSERT INTO roundstate (gameid, round, roundstarttime, action, data1, go, userturn, word) VALUES ($gameid,$round,$time,'$type','$guess',$go,'$userturn','$word')";
		$glDb->query($SQL);

		if(strtolower($guess) == $word) {
			// Get the current team's points
			$SQL = "SELECT team FROM gameusers WHERE gameid = $gameid AND username = '$userturn'";
			$team = $glDb->getOne($SQL);
			$SQL = "SELECT points" . strtolower($team) ." FROM gamestate WHERE gameid = $gameid";
			$points = $glDb->getOne($SQL);
			$points++;
			$SQL = "UPDATE gamestate SET points" . strtolower($team) . " = $points WHERE gameid = $gameid";
			$glDb->query($SQL);
			
			// Get a new word (the copy of above)
			$SQL = "SELECT word FROM wordlist";
			$words = $glDb->query($SQL);
			$wordIndex = rand()%($words->numRows());
			for($i = 0; $i<$wordIndex; $i++) {
				$words->fetchRow();
			}
			$theWord = $words->fetchRow();
			$word = $theWord[0];
			
			$SQL = "INSERT INTO roundstate (gameid, round, roundstarttime, action, data1, data2, go, userturn, word) VALUES ($gameid,$round,$time,'$type','$dragid','$dragsrc',$go,'$userturn','$word')";
			$glDb->query($SQL);
		}
		
	}
?>
